const http = require('http');
const fs = require('fs');
const path = require('path');

console.log('Starting simple server...');
console.log('Base directory:', __dirname);

const server = http.createServer((req, res) => {
	console.log('Received request for:', req.url);

	// Set the base directory to the parent directory of the scripts folder
	const baseDir = path.resolve(__dirname, '..');

	// Remove query parameters from the URL
	const cleanUrl = req.url.split('?')[0];

	// Determine file path based on request URL
	let filePath;
	if (cleanUrl === '/' || cleanUrl === '/index.html') {
		filePath = path.join(baseDir, 'iframe', 'home.html');
	} else {
		// Serve the requested file relative to the base directory
		filePath = path.join(baseDir, cleanUrl);
	}

	console.log('Attempting to serve:', filePath);

	// Check if path exists
	fs.stat(filePath, (err, stats) => {
		if (err) {
			console.error('ERROR: Path not found:', filePath);
			res.writeHead(404, { 'Content-Type': 'text/plain' });
			res.end('Error: File not found');
			return;
		}

		// If it's a directory, try to serve index.html or show error
		if (stats.isDirectory()) {
			const indexPath = path.join(filePath, 'index.html');
			fs.access(indexPath, fs.constants.F_OK, (err) => {
				if (err) {
					console.error('ERROR: Directory has no index.html:', filePath);
					res.writeHead(403, { 'Content-Type': 'text/plain' });
					res.end('Error: Directory listing not allowed');
				} else {
					// Serve the directory's index.html
					serveFile(indexPath, res);
				}
			});
		} else {
			// It's a file, serve it
			serveFile(filePath, res);
		}
	});
});

// Helper function to read and serve a file
function serveFile(filePath, res) {
	fs.readFile(filePath, (err, data) => {
		if (err) {
			console.error('ERROR reading file:', err.message);
			res.writeHead(500, { 'Content-Type': 'text/plain' });
			res.end('Error: ' + err.message);
		} else {
			// Determine content type based on file extension
			let contentType = 'text/plain';
			const ext = path.extname(filePath).toLowerCase();

			switch (ext) {
				case '.html':
					contentType = 'text/html';
					break;
				case '.css':
					contentType = 'text/css';
					break;
				case '.js':
					contentType = 'application/javascript';
					break;
				case '.json':
					contentType = 'application/json';
					break;
				case '.png':
					contentType = 'image/png';
					break;
				case '.jpg':
				case '.jpeg':
					contentType = 'image/jpeg';
					break;
				case '.gif':
					contentType = 'image/gif';
					break;
				case '.svg':
					contentType = 'image/svg+xml';
					break;
			}

			console.log('SUCCESS: File served successfully:', filePath);
			res.writeHead(200, { 'Content-Type': contentType });
			res.end(data);
		}
	});
}

// Change port from 8000 to 8080
const PORT = 8080;
server.listen(PORT, () => {
	console.log('Server running at http://localhost:' + PORT + '/');
	console.log('Serving files from:', path.resolve(__dirname, '..'));
});
